import { Context } from 'koa';
import { query, queryOne } from '../database/mysql';
import { Member, MemberLevelRelation } from '../database/models';
import { utils, valids } from '../utils/utils';
import { success, error } from '../utils/response';
import { ResponseCode } from '../config/responseCode';

/**
 * 创建会员
 */
export async function createMember(ctx: Context): Promise<void> {
  const { name, phone, email, gender, birthday, address, level_id } = ctx.request.body as {
    name?: string;
    phone?: string;
    email?: string;
    gender?: number;
    birthday?: string;
    address?: string;
    level_id?: string;
  };

  if (!name) {
    error(ctx, ResponseCode.BAD_REQUEST, '会员姓名不能为空');
    return;
  }

  // 校验邮箱格式
  if (email && !valids.isEmail(email)) {
    error(ctx, ResponseCode.BAD_REQUEST, '邮箱格式不正确');
    return;
  }

  // 校验手机号格式
  if (phone && !valids.isMobile(phone)) {
    error(ctx, ResponseCode.BAD_REQUEST, '手机号格式不正确');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  // 创建会员
  const memberId = utils.generateUUID();
  await query(
    `INSERT INTO members (id, user_id, name, phone, email, gender, birthday, address, status)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)`,
    [
      memberId,
      userId,
      name,
      phone || null,
      email || null,
      gender || 0,
      birthday || null,
      address || null,
    ]
  );

  // 添加等级关系（默认一对一）
  if (level_id) {
    const relationId = utils.generateUUID();
    await query(
      'INSERT INTO member_level_relations (id, member_id, level_id) VALUES (?, ?, ?)',
      [relationId, memberId, level_id]
    );
  }

  const newMember = await queryOne<Member>('SELECT * FROM members WHERE id = ?', [memberId]);
  success(ctx, newMember);
}

/**
 * 更新会员
 */
export async function updateMember(ctx: Context): Promise<void> {
  const { id, name, phone, email, gender, birthday, address, status, level_id } = ctx.request.body as {
    id?: string;
    name?: string;
    phone?: string;
    email?: string;
    gender?: number;
    birthday?: string;
    address?: string;
    status?: number;
    level_id?: string;
  };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '会员ID不能为空');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  // 检查会员是否存在且属于当前用户
  const member = await queryOne<Member>('SELECT * FROM members WHERE id = ? AND user_id = ?', [id, userId]);
  if (!member) {
    error(ctx, ResponseCode.MEMBER_NOT_FOUND);
    return;
  }

  // 更新会员信息
  const updates: string[] = [];
  const params: any[] = [];

  if (name !== undefined) {
    updates.push('name = ?');
    params.push(name);
  }
  if (phone !== undefined) {
    // 校验手机号格式
    if (!valids.isMobile(phone)) {
      error(ctx, ResponseCode.BAD_REQUEST, '手机号格式不正确');
      return;
    }
    updates.push('phone = ?');
    params.push(phone);
  }
  if (email !== undefined) {
    // 校验邮箱格式
    if (!valids.isEmail(email)) {
      error(ctx, ResponseCode.BAD_REQUEST, '邮箱格式不正确');
      return;
    }
    updates.push('email = ?');
    params.push(email);
  }
  if (gender !== undefined) {
    updates.push('gender = ?');
    params.push(gender);
  }
  if (birthday !== undefined) {
    updates.push('birthday = ?');
    params.push(birthday);
  }
  if (address !== undefined) {
    updates.push('address = ?');
    params.push(address);
  }
  if (status !== undefined) {
    updates.push('status = ?');
    params.push(status);
  }

  if (updates.length > 0) {
    params.push(id, userId);
    await query(`UPDATE members SET ${updates.join(', ')} WHERE id = ? AND user_id = ?`, params);
  }

  // 更新等级关系
  if (level_id !== undefined) {
    // 删除旧关系
    await query('DELETE FROM member_level_relations WHERE member_id = ?', [id]);
    
    // 添加新关系
    if (level_id) {
      const relationId = utils.generateUUID();
      await query(
        'INSERT INTO member_level_relations (id, member_id, level_id) VALUES (?, ?, ?)',
        [relationId, id, level_id]
      );
    }
  }

  const updatedMember = await queryOne<Member>('SELECT * FROM members WHERE id = ? AND user_id = ?', [id, userId]);
  if (!updatedMember) {
    error(ctx, ResponseCode.MEMBER_NOT_FOUND);
    return;
  }
  success(ctx, updatedMember);
}

/**
 * 删除会员
 */
export async function deleteMember(ctx: Context): Promise<void> {
  const { id } = ctx.request.body as { id?: string };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '会员ID不能为空');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  // 检查会员是否存在且属于当前用户
  const member = await queryOne<Member>('SELECT * FROM members WHERE id = ? AND user_id = ?', [id, userId]);
  if (!member) {
    error(ctx, ResponseCode.MEMBER_NOT_FOUND);
    return;
  }

  // 删除等级关系
  await query('DELETE FROM member_level_relations WHERE member_id = ?', [id]);
  
  // 删除会员（确保只删除属于当前用户的会员）
  await query('DELETE FROM members WHERE id = ? AND user_id = ?', [id, userId]);

  success(ctx, { message: '删除成功' });
}

/**
 * 查询会员列表
 */
export async function getMemberList(ctx: Context): Promise<void> {
  const { page = 1, pageSize = 10, name, phone, status } = ctx.request.body as {
    page?: number;
    pageSize?: number;
    name?: string;
    phone?: string;
    status?: number;
  };

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  let sql = 'SELECT * FROM members WHERE user_id = ?';
  const params: any[] = [userId];

  if (name) {
    sql += ' AND name LIKE ?';
    params.push(`%${name}%`);
  }
  if (phone) {
    sql += ' AND phone LIKE ?';
    params.push(`%${phone}%`);
  }
  if (status !== undefined) {
    sql += ' AND status = ?';
    params.push(status);
  }

  sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
  const offset = (page - 1) * pageSize;
  params.push(pageSize, offset);

  const members = await query<Member>(sql, params);
  
  // 获取每个会员的等级信息
  const memberIds = members.map(m => m.id);
  let levelRelations: MemberLevelRelation[] = [];
  if (memberIds.length > 0) {
    const placeholders = memberIds.map(() => '?').join(',');
    levelRelations = await query<MemberLevelRelation>(
      `SELECT * FROM member_level_relations WHERE member_id IN (${placeholders})`,
      memberIds
    );
  }

  const levelMap = new Map(levelRelations.map(r => [r.member_id, r.level_id]));

  const memberList = members.map(member => ({
    ...member,
    level_id: levelMap.get(member.id) || null,
  }));

  const totalResult = await queryOne<{ count: number }>(
    'SELECT COUNT(*) as count FROM members WHERE user_id = ?' + 
    (name ? ' AND name LIKE ?' : '') + 
    (phone ? ' AND phone LIKE ?' : '') + 
    (status !== undefined ? ' AND status = ?' : ''),
    params.slice(0, -2)
  );

  success(ctx, {
    list: memberList,
    total: totalResult?.count || 0,
    page,
    pageSize,
  });
}

/**
 * 查询会员详情
 */
export async function getMemberDetail(ctx: Context): Promise<void> {
  const { id } = ctx.request.body as { id?: string };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '会员ID不能为空');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  const member = await queryOne<Member>('SELECT * FROM members WHERE id = ? AND user_id = ?', [id, userId]);
  if (!member) {
    error(ctx, ResponseCode.MEMBER_NOT_FOUND);
    return;
  }

  // 获取等级信息
  const levelRelation = await queryOne<MemberLevelRelation>(
    'SELECT * FROM member_level_relations WHERE member_id = ?',
    [id]
  );

  success(ctx, {
    ...member,
    level_id: levelRelation?.level_id || null,
  });
}

